package org.sheresam.springhbnjpa.test2.web;

import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.core.env.PropertySource;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.filter.RequestContextFilter;
import org.springframework.web.servlet.DispatcherServlet;

public class ApplicationWebAppInitializer implements WebApplicationInitializer {

//    String[] configLocations = { "classpath:springhbnjpa-beans.xml", "classpath:spring-beans.xml", "classpath:applicationContext-security.xml" };
//    String[] configLocations = { "classpath:applicationContext-security.xml" };
    
    /**
     * Register and configure all Servlet container components necessary to
     * power the Greenhouse web application.
     */
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        System.out.println("ApplicationWebAppInitializer.onStartup()");

        // this didn't work either
//        sc.setInitParameter("spring.profiles.acctive", "derby_tomcatcp_pool,jpa,proddata");
        
        // Create the 'root' Spring application context
//        XmlWebApplicationContext  root = new XmlWebApplicationContext ();
        
        // AnnotationConfigWebApplicationContext expects class instead of xml file, little bugger
//        root.setConfigLocations(configLocations);
        
        
        AnnotationConfigWebApplicationContext rootSpringContext = new AnnotationConfigWebApplicationContext();
        
        // for some reason this didn't work still using web.xml for now
//        rootSpringContext.getEnvironment().setDefaultProfiles("derby_tomcatcp_pool,jpa,proddata");
        
        rootSpringContext.setServletContext(servletContext);
        rootSpringContext.scan("org.sheresam.springhbnjpa", "org.sheresam.springhbnjpa.test2", "org.springframework.security");
        
        
        
        
        PropertySource<Object> ps = new SpringCustomPropertySource("testsource");
        rootSpringContext.getEnvironment().getPropertySources().addFirst(ps);

        // Manages the lifecycle of the root application context
        servletContext.addListener(new ContextLoaderListener(rootSpringContext));

        // Allows attributes to be accessed on the next request
        servletContext.addFilter("localizationFilter", RequestContextFilter.class).addMappingForUrlPatterns(null, false, "/*");

//        // Enables support for DELETE and PUT request methods with web browser
//        // clients
//        sc.addFilter("hiddenHttpMethodFilter", HiddenHttpMethodFilter.class).addMappingForUrlPatterns(null, false, "/*");

        // Secures the application
        // always expects springSecurityFilterChain as bean name
        DelegatingFilterProxy securityFilter = new DelegatingFilterProxy("springSecurityFilterChain");
        servletContext.addFilter("securityFilter", securityFilter).addMappingForUrlPatterns(null, false, "/*");
        
        // Open view JPA Entity manager 
        servletContext.addFilter("springJPAFilter", OpenEntityManagerInViewFilter.class).addMappingForUrlPatterns(null, false, "/*");
        
        // Enables encoding on the request & response object to UTF-8
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        encodingFilter.setEncoding("UTF-8");
        encodingFilter.setForceEncoding(true);
        servletContext.addFilter("encoding-filter", encodingFilter).addMappingForUrlPatterns(null, false, "/*");

        // Handles requests into the application
        ServletRegistration.Dynamic appServlet = servletContext.addServlet("springhbnjpatest", new DispatcherServlet(rootSpringContext));
        appServlet.setLoadOnStartup(1);
        Set<String> mappingConflicts = appServlet.addMapping("/secure/*");
        if (!mappingConflicts.isEmpty()) {
            throw new IllegalStateException("'appServlet' could not be mapped to '/' due "
                    + "to an existing mapping. This is a known issue under Tomcat versions "
                    + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278");
        }

    }

}
